package com.JackTang.fruit.servlets;

import com.JackTang.fruit.dao.FruitDAO;
import com.JackTang.fruit.dao.impl.FruitDAOImpl;
import com.JackTang.fruit.pojo.Fruit;
import com.myssm.myspringmvc.ViewBaseServlet;
import com.myssm.util.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * @author Jack Tang
 * @description
 * @create 2023-05-07 15:55
 */
@WebServlet("/fruit.do")
public class FruitServlet extends ViewBaseServlet {

    private FruitDAO fruitDAO = new FruitDAOImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置编码
        req.setCharacterEncoding("utf-8");

        String operate = req.getParameter("operate");
        if (StringUtil.isEmpty(operate)){
            //默认初始首页是 index页面
            operate = "index";
        }

        switch(operate){
            case "index":
                index(req,resp);
                break;
            case "add":
                add(req, resp);
                break;
            case "del":
                del(req,resp);
                break;
            case "edit":
                edit(req,resp);
                break;
            case "update":
                update(req,resp);
                break;
            default :
                throw new RuntimeException("operate的值非法！");
        }
    }

    private void index(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


        // 设置当前页默认值为 1
        Integer pageNo = 1;

        // 将 pageNo 保存到session作用域中
        HttpSession session = req.getSession();
        String oper = req.getParameter("oper");
        // 如果 oper!=null 说明 通过表单的查询按钮点击过来的
        // 如果 oper 为空值，说明 不是通过表单的查询按钮点击过来的

        String keyword = null;
        if (StringUtil.isNotEmpty(oper) && "search".equals(oper)){
            //说明是点击表单查询发送过来的请求
            //此时，pageNo应该还原为 1，keyword 应该从请求参数中获取
            pageNo = 1; // 这里为什么设置为 1 呢？ 因为你在查询完成之后还是得跳转到你所查询后结果的第一页。
            keyword = req.getParameter("keyword");
            // 如果keyword为null，需要设置为空字符串""，否则查询时会拼接成 %null% ，我们期望的是 %%
            if (StringUtil.isEmpty(keyword)) {
                keyword = "";
            }
            // 将keyword保存（覆盖）到session中
            session.setAttribute("keyword",keyword);
        }else {
            //说明不是点击表单查询发送过来的请求（比如点击下面的上一页下一页或者直接在地址栏输入网址）
            //此时keyword应该从session作用域获取
            // 获取页码
            String pageNoStr = req.getParameter("pageNo");
            if (StringUtil.isNotEmpty(pageNoStr)){
                pageNo = Integer.parseInt(pageNoStr); // 如果从请求中读取 pageNo ，则类型转换，否则，pageNo 默认就是 1
            }
            // 如果不是点击的查询按钮，那么查询时基于现有的 keyword 进行查询
            Object keywordObj = session.getAttribute("keyword");
            if (keywordObj != null){
                keyword = (String) keywordObj;
            }else {
                keyword = "";
            }

        }

        // 重新更新 pageNo 的值
        session.setAttribute("pageNo",pageNo);

        FruitDAO fruitDAO = new FruitDAOImpl();
        List<Fruit> fruitList = fruitDAO.getFruitList(keyword,pageNo);
        session.setAttribute("fruitList",fruitList);

        int fruitCount = fruitDAO.getFruitCount(keyword);
        int pageEnd = (fruitCount-1+5)/5;
        session.setAttribute("pageEnd",pageEnd);


        // 此处的视图名称是 index
        // 那么 thymeleaf 会将这个 逻辑视图名称 对应到 物理视图 名称上去
        // 逻辑视图名称： index
        // 物理视图名称： view-prefix + 逻辑视图名称 + view-suffix
        // 所以真实的视图名称是： /index.html
        super.processTemplate("index",req,resp);

    }

    private void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.setCharacterEncoding("utf-8");

        String fname = req.getParameter("fname");
        String priceStr = req.getParameter("price");
        int price = Integer.parseInt(priceStr);
        String fcountStr = req.getParameter("fcount");
        int fcount = Integer.parseInt(fcountStr);
        String remark = req.getParameter("remark");

        fruitDAO.addFruit(new Fruit(0,fname,price,fcount,remark));

        resp.sendRedirect("fruit.do");
    }

    private void del(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String fidStr = req.getParameter("fid");
        int fid = Integer.parseInt(fidStr);
        fruitDAO.deleteFruit(fid);

        resp.sendRedirect("fruit.do");
    }

    private void edit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String fidStr = req.getParameter("fid");
        if (StringUtil.isNotEmpty(fidStr)){
            int fid = Integer.parseInt(fidStr);
            Fruit fruit = fruitDAO.getFruitByFid(fid);
            req.setAttribute("fruit",fruit);
            super.processTemplate("edit",req,resp);
        }
    }

    private void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 设置编码
        req.setCharacterEncoding("utf-8");

        // 获取参数
        String fidStr = req.getParameter("fid");
        int fid = Integer.parseInt(fidStr);
        String fname = req.getParameter("fname");
        String priceStr = req.getParameter("price");
        int price = Integer.parseInt(priceStr);
        String fcountStr = req.getParameter("fcount");
        int fcount = Integer.parseInt(fcountStr);
        String remark = req.getParameter("remark");

        // 更新
        fruitDAO.updateFruit(new Fruit(fid,fname,price,fcount,remark));

        // 资源跳转
        //super.processTemplate("index",req,resp);
        // 相当于 req.getRequestDispatcher("index.html").forward(req,resp);
        // 此处需要重定向，目的就是重新给Indexservlet发请求，重新获取fruitList，然后覆盖到session中，
        //这样index.html页面上显示的session中的数据才是最新的
        resp.sendRedirect("fruit.do");
    }
}